<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use App\Models\Admin\Store;
use App\Models\Admin\GoodType;
use App\Models\Admin\Grade;
use App\Models\Admin\Share;
use App\Models\Admin\GoodPrice;
use App\Models\Admin\BonusPoolTwo;
use App\Common\ValidateHandler;
use App\Common\AliossHandler;
use Auth, DB;

class Good extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'good_type_id', 'sale_type',
        'title', 'cover', 'describe', 'detail', 
        'sku', 'base_price', 'weight', 'status', 
        'jf', 'jf_send', 'jgz', 'bonus_pool_one', 'share_gold', 'share_money', 'cost', 'sort', 'is_delivery_fee', 'list_num',
        'created_at', 'updated_at','new_model','is_loop','arr_loop','added','bd_index','bd_member_pool','bd_partner_one','bd_partner_two','bd_order_pool'
    ];

    public function getList($data)
    {
        $pageSize = $data['pageSize'];
        $storeId = Auth::guard('admin')->user()->store_id;
        $requestStoreId = $data['storeId'];

        if ($storeId == 0) {
            // 管理员查看全部店铺分类列表 按店铺排序
            if ($requestStoreId == 0) {
                $data = $this->orderBy('store_id')->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
            } else {
                $data = $this->where('store_id', $requestStoreId)->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
            }
        } else {
            // 店家只能查看自己店的分类
            $data = $this->where('store_id', $storeId)->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
        }
        $data = $this->handleData($data);

        return $this->success($data);
    }

    private function handleData($data)
    {
        $store = new Store;
        $stores = $store->select(['id', 'title'])->get()->toArray();
        $stores = key_val($stores);
        $stores[0] = ['id' => 0, 'title' => '无店铺'];

        foreach ($data['data'] as $k => $good) {
            $data['data'][$k]['store'] = $stores[$good['store_id']];
            $data['data'][$k]['good_type'] = GoodType::find($good['good_type_id'])->title;
            $status = '';
            if ($good['status'] == 1) {
                $status = '上架';
            } else if($good['status'] == 2) {
                $status = '下架';
            } else {
                $status = '售罄';
            }
            $data['data'][$k]['status_title'] = $status;
            $data['data'][$k]['cover'] = $this->getCover($good['cover']);
            $data['data'][$k]['share_money'] = $good['share_money'] / 100;
        }

        return $data;
    }

    public function handleInit($data)
    {
        $arr = [];
        $storeId = Auth::guard('admin')->user()->store_id;
        if ($storeId == 0) {
            // 管理员选择店铺id后初始化数据
            if (!empty($data['good_id'])) {
                $storeId = $this->find($data['good_id'])->store_id;
            } else {
                $storeId = $data['store_id'];
            }
        }
        $arr['stores'] = Store::select(['id', 'title'])->get()->toArray();
        if ($storeId != 0) {
            // 判断分享经济
            $share = Share::where('store_id', $storeId)->first();
            if (empty($share))
                return $this->error(['info' => '请先完善店铺分享经济', 'data' => $arr], 20002);

            $arr['good_types'] = GoodType::where('store_id', $storeId)->select(['id', 'title'])->where('status', 1)->get()->toArray();
            $grade = new Grade;
            $arr['grade'] = $grade->gradeOptions($storeId);
            if (empty($arr['good_types']))
                return $this->error(['info' => '请先添加商品分类', 'data' => $arr], 20002);
            if (empty($arr['grade'])) 
                return $this->error(['info' => '请先完善店铺会员等级', 'data' => $arr], 20002);
            $arr['grade'] = array_slice($arr['grade'],0,1);//只保留会员价格
            $arr['share_type'] = $share->type;
            $arr['share_method'] = $share->method;

            $inputRadio = [];
            if($share->type == 3 && $share->method == 1){
                $num = $share['num'];
                for ($x = 1; $x <= $num; $x++) {
                    $inputRadio[$x]['rela'] = $x;
                    $inputRadio[$x]['text'] = $x == 1 ? '码上折' : '折上折';//'第 '.$x.' 代';
                    $inputRadio[$x]['radio'] = (json_decode($share->radio)->$x);
                }
            }
            
            $arr['share'] = $inputRadio;
        }

        return $this->success($arr);
    }

    public function handle($data)
    {
        $arr = [];
        $id = $data['id'];
        $arr['good_type_id'] = $data['good_type_id'];
        $arr['sale_type'] = $data['sale_type'];
        $arr['title'] = $data['title'];
        $arr['cover'] = $data['cover'];
        $arr['describe'] = empty($data['describe']) ? '' : $data['describe'];
        $arr['detail'] = empty($data['detail']) ? '' : $data['detail'];
        $arr['sku'] = empty($data['sku']) ? '' : $data['sku'];
        $arr['base_price'] = $data['base_price'] * 100;
        $arr['weight'] = empty($data['weight']) ? 0 : $data['weight'];
        $arr['status'] = $data['status'];
        $arr['jf'] = $data['jf'] * 100;
        $arr['jf_send'] = empty($data['jf_send']) ? 0 : $data['jf_send'] * 100;
        $arr['cost'] = $data['cost'] * 100;
        $arr['sort'] = empty($data['sort']) ? 0 : $data['sort'];
        $arr['is_delivery_fee'] = $data['is_delivery_fee'];
        $arr['list_num'] = empty($data['list_num']) ? 0 : $data['list_num'];
        $arr['share_money'] = empty($data['share_money']) ? 0 : $data['share_money'] * 100;
        $arr['share_gold'] = empty($data['shares']) ? : json_encode($data['shares']); 
        
        $resultData = $this->checkNewModel($arr,$data);
        $arr = $resultData['arr'];
        $data = $resultData['data'];

        $goodPrice = $data['price'];
        // $share = $data['share'];//这个是null 后续再查看此函数是否有用
        // return $this->error(['info' => $share]);
        $shareGold = $data['shares'];

        $userStoreId = Auth::guard('admin')->user()->store_id; //用户店铺id 0为管理员
        if ($userStoreId == 0) {
            // 管理员提交
            $arr['store_id'] = empty($data['store_id']) ? 0 : $data['store_id'];
            if ($arr['store_id'] == 0) return $this->error(['info' => '请选择店铺']);
        } else {
            $arr['store_id'] = $userStoreId;
        }

        $result = $this->validateData($arr, $goodPrice, $shareGold);
        if (!$result['res'])
            return $this->error($result);

        $store = new Store;
        $storeInfo = $store->where('id',$arr['store_id'])->first();
        if($data['new_model'] == 1 && $data['jf'] > $data['team_fund']){
            return $this->error(['info' => '抵扣积分不能超过教育培训基金']);
        }

        $share_gold = [];
        foreach ($shareGold as $key => $value) {
            $share_gold[$value['rela']] = $value["radio"];            
        }
        
        $arr['share_gold'] = empty($share_gold) ? NULL : json_encode($share_gold);
        if ($id == 'new') {
            $res = $this->insertData($arr, $goodPrice, $data);
        } else {
            $res = $this->updateData($arr, $goodPrice, $id, $data);
        }
        if (!$res['res']) {
            return $this->error(['info' => '操作失败']);
        }
        return $this->success(['info' => '操作成功', 'data' => $arr]);
    }

    //新报单模式 新增逻辑 尽量少动原代码
    private function checkNewModel($arr,$data){
        $arr['new_model'] =  $data['new_model'];
        if($data['new_model'] == 1){//1为旧模式 
            //旧模式数据
            $arr['jgz'] = $data['jgz'] * 100; 
            $arr['bonus_pool_one'] = $data['bonus_pool_one'] * 100;

            $bonus_pool_two = (int)$data['bonus_pool_two']*100;
            $team_month = (int)$data['team_month']*100;
            $team_year = (int)$data['team_year']*100;
            $team_recommend = (int)$data['team_recommend']*100;
            $team_fund = (int)$data['team_fund']*100;
            $sum = $team_month + $team_year + $team_recommend + $team_fund;
            if($sum != $bonus_pool_two){
                return $this->error(['info' => '合伙人折扣下4项奖池分配不达标']);
            }

            //新模式数据恢复默认
            $arr['is_loop'] =  0;
            $arr['arr_loop'] = json_encode(['1'=>0]);
            $arr['added'] =  0;
            $arr['bd_index'] = 0;
            $arr['bd_member_pool'] = 0;
            $arr['bd_partner_one'] = 0;
            $arr['bd_partner_two'] = 0;
            $arr['bd_order_pool'] = 0;
            
        }else{
            //新报单模式新添加属性
            $arr['new_model'] =  $data['new_model'];
            $arr['is_loop'] =  $data['is_loop'];
            $arr['added'] =  empty($data['added']) ? 0 : $data['added'] * 100;
            $arr['bd_index'] = empty($data['bd_index']) ? 0 : $data['bd_index'] * 100;
            $arr['bd_member_pool'] = $data['bd_member_pool'] * 100;
            $arr['bd_partner_one'] = $data['bd_partner_one'] * 100;
            $arr['bd_partner_two'] = $data['bd_partner_two'] * 100;
            $arr['bd_order_pool'] = $data['bd_order_pool'] * 100;

            $arr_loop = [];
            foreach ($data['arr_loop'] as $key => $value) {
                    $arr_loop[$key+1] = empty($value) ? 0 : $value*100;
            }
            $arr['arr_loop'] = json_encode($arr_loop);    

            //旧模式数据恢复默认
            $arr['jgz'] = 0; 
            $arr['bonus_pool_one'] = 0;
            $data['bonus_pool_two'] = 0;
            $data['team_month'] = 0;
            $data['team_year'] = 0;
            $data['team_recommend'] = 0;
            $data['team_fund'] = 0;
        }
        $result = [];
        $result['arr'] = $arr;
        $result['data'] = $data;
        return $result;
    }

    private function insertData($data, $price, $queryData)
    {
        DB::beginTransaction();
        try {       
            $res = $this->create($data);
            $goodId = $res->id;
            $storeId = $res->store_id;

            $goodPrice = new GoodPrice;
            $goodPrice->insertData($price, $storeId, $goodId);

            //2号奖金池
            $two = new BonusPoolTwo;
            $bonus_pool_two = [];
            $bonus_pool_two['good_id'] = $goodId;
            $bonus_pool_two['store_id'] = $storeId;
            $bonus_pool_two['bonus_pool_two'] = $queryData['bonus_pool_two']*100;
            $bonus_pool_two['team_month'] = $queryData['team_month']*100;
            $bonus_pool_two['team_year'] = $queryData['team_year']*100;
            $bonus_pool_two['team_recommend'] = $queryData['team_recommend']*100;
            $bonus_pool_two['team_fund'] = $queryData['team_fund']*100;
            $two->create($bonus_pool_two);

            DB::commit();
            return ['res' => true];
        } catch (\Exception $e) {
            DB::rollBack();
            return ['res' => false];
        }
    }

    private function updateData($data, $price, $id, $queryData)
    {
        DB::beginTransaction();
        try {
            $res = $this->where('id', $id)->update($data);
            $storeId = $this->find($id)->store_id;

            $goodPrice = new GoodPrice;
            $goodPrice->updateData($price, $storeId, $id);

            //2号奖金池
            $two = new BonusPoolTwo;
            $bonus_pool_two = [];
            $bonus_pool_two['good_id'] = $id;
            $bonus_pool_two['store_id'] = $storeId;
            $bonus_pool_two['bonus_pool_two'] = $queryData['bonus_pool_two']*100;
            $bonus_pool_two['team_month'] = $queryData['team_month']*100;
            $bonus_pool_two['team_year'] = $queryData['team_year']*100;
            $bonus_pool_two['team_recommend'] = $queryData['team_recommend']*100;
            $bonus_pool_two['team_fund'] = $queryData['team_fund']*100;
            $two->updateData($bonus_pool_two);

            DB::commit();
            return ['res' => true];
        } catch (\Exception $e) {
            DB::rollBack();
            return ['res' => false];
        }
    }

    private function validateData($data, $price, $shareGold)
    {
        $arr = [
            0 => [
                'name' => '商品名称',
                'value' => $data['title'],
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '商品分类',
                'value' => $data['good_type_id'],
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '商品零售价',
                'value' => $data['base_price'],
                'func' => 'is_empty'
            ],
            3 => [
                'name' => '抵扣积分上限',
                'value' => $data['jf'],
                'func' => 'rangeNum',
                'min' => 0
            ],
            4 => [
                'name' => '设定成本',
                'value' => $data['cost'],
                'func' => 'is_empty'
            ],
            5 => [
                'name' => '寄邮类型',
                'value' => $data['is_delivery_fee'],
                'func' => 'is_empty'
            ],
            6 => [
                'name' => '销售类型',
                'value' => $data['sale_type'],
                'func' => 'is_empty'
            ],
            7 => [
                'name' => '商品封面',
                'value' => $data['cover'],
                'func' => 'is_empty'
            ],
            8 => [
                'name' => '商品价格',
                'value' => $price,
                'func' => 'is_empty',
            ],
            9 => [
                'name' => '商品价格',
                'value' => $price,
                'func' => 'good_price',
                'store_id' => $data['store_id']
            ]
        ];
        $shareModel = Share::where('store_id', $data['store_id'])->first();
        $shareType = $shareModel->type;
        $shareMethod = $shareModel->method;
        if ($shareType == 3 && $shareMethod == 1) {
            $arr[] = [
                'name' => '商品分享金额',
                'value' => $shareGold,
                'func' => 'is_empty',
                'store_id' => $data['store_id']
            ];
        }

        if($data['new_model'] == 1){
            $arr[] = [
                'name' => '富利指数',
                'value' => $data['jgz'],
                'func' => 'is_empty'
            ];
            $arr[] = [
                'name' => '会员折扣',
                'value' => $data['bonus_pool_one'],
                'func' => 'rangeNum',
                'min' => 0
            ];
        }
        return ValidateHandler::do($arr);
    }

    public function getCover($fileName)
    {
        return AliossHandler::read('good', $fileName);
    }

    public function loadData($id)
    {
        $good = $this->find($id)->toArray();
        $arr = ['url' => $this->getCover($good['cover']),'origin' => $good['cover']];
        $good['files'][] = $arr;

        $goodPrice = GoodPrice::where('store_id', $good['store_id'])->where('good_id', $good['id'])->select(['price'])->get()->toArray();
        $bonusPoolTwo = BonusPoolTwo::where('store_id', $good['store_id'])->where('good_id', $good['id'])->first();
        $good['base_price'] = $good['base_price'] / 100;
        $good['jf'] = $good['jf'] / 100;
        $good['jf_send'] = $good['jf_send'] / 100;
        $good['cost'] = $good['cost'] / 100;
        $good['share_money'] = $good['share_money'] / 100;
        $good['jgz'] = $good['jgz'] / 100;
        

        if($good['new_model'] == 0){
                //新报单模式新增属性
                $loop = [];
                if(empty($good['arr_loop'])){
                    $good['arr_loop'] = [0=>'']; 
                }else{
                    $arr_loop = json_decode($good['arr_loop'],true);
                
                    $num = count($arr_loop);
                    for ($i=0; $i < $num; $i++) { 
                        $loop[$i] = $arr_loop[$i+1]/100;   
                    }
                    $good['arr_loop'] = $loop;
                }
 
                $good['added'] =  $good['added'] / 100;
                $good['bd_index'] = $good['bd_index'] / 100;
                $good['bd_member_pool'] = $good['bd_member_pool'] / 100;
                $good['bd_partner_one'] = $good['bd_partner_one'] / 100;
                $good['bd_partner_two'] = $good['bd_partner_two'] / 100;
                $good['bd_order_pool'] = $good['bd_order_pool'] / 100;
        }else{
            $good['bonus_pool_one'] = $good['bonus_pool_one'] / 100;
            $good['bonus_pool_two'] = $bonusPoolTwo['bonus_pool_two'] / 100;
            $good['team_month'] = $bonusPoolTwo['team_month'] / 100;
            $good['team_year'] = $bonusPoolTwo['team_year'] / 100;
            $good['team_recommend'] = $bonusPoolTwo['team_recommend'] / 100;
            $good['team_fund'] = $bonusPoolTwo['team_fund'] / 100;
        }


        $good['price'] = array_column($goodPrice, 'price');
        foreach ($good['price'] as $k => $v) {
            $good['price'][$k] = $good['price'][$k] / 100;
        }
        $shareModel = Share::where('store_id', $good['store_id'])->first();
        
        $inputRadio = [];
        $num = $shareModel['num'];
        for ($x = 1; $x <= $num; $x++) {
            $inputRadio[$x]['rela'] = $x;
            $inputRadio[$x]['text'] = $x == 1 ? '码上折' : '折上折';//'第 '.$x.' 代';
            $inputRadio[$x]['radio'] = empty($good['share_gold']) ? 0 : (json_decode($good['share_gold'])->$x);
        }
        $good['shares'] = $inputRadio;

        return $this->success($good);
    }

    public function deleteAction($id)
    {
        $this->find($id)->delete();
        GoodPrice::where('good_id', $id)->delete();
        return $this->success(['info' => '删除成功']);
    }
}
